//图片存储
const multer = require('multer');
const qiniu = require('qiniu');
const {Kodo} = require('../config/dbconfig');
const express = require("express");
const fs = require('fs');
const path = require('path');
const {get} = require("axios");
const router = express.Router();
const mac = new qiniu.auth.digest.Mac(Kodo.accessKey, Kodo.secretKey);
const options = {
    scope: Kodo.bucket,
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
// 配置 multer 中间件，用于处理上传的文件
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});
const upload = multer({storage: storage});
// 配置七牛云存储空间管理对象
const config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z2; // 选择华南区域
const formUploader = new qiniu.form_up.FormUploader(config);

// 下载图片并上传到七牛云
async function uploadImageToQiniu(googleImageUrl) {
    try {
        // 1. 下载 Google 头像图片
        const response = await get(googleImageUrl, {responseType: 'arraybuffer'});
        // 2. 创建文件夹（如果不存在）
        const uploadDir = path.join(__dirname, 'temp(临时文件)');
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir);  // 如果文件夹不存在，则创建
        }
        // 3. 保存图片到临时文件
        const tempFilePath = path.join(uploadDir, 'temp_image.jpg');
        fs.writeFileSync(tempFilePath, response.data);

        // 4. 上传图片到七牛云
        const key = `avatars/${Date.now()}-${Math.random().toString(36).substr(2, 9)}.jpg`;  // 生成唯一的文件名
        const putExtra = new qiniu.form_up.PutExtra();

        return new Promise((resolve, reject) => {
            formUploader.putFile(uploadToken, key, tempFilePath, putExtra, (respErr, respBody, respInfo) => {
                if (respErr) {
                    reject('Failed to upload image to Qiniu Cloud');
                    return;
                }

                if (respInfo.statusCode === 200) {
                    const imageUrl = `https://cdn.xuxiao888.com/${key}`;
                    resolve(imageUrl);  // 返回七牛云的图片 URL
                } else {
                    reject('Failed to upload image to Qiniu Cloud');
                }
            });
        });
    } catch (error) {
        console.error('Error during image upload process:', error);
        throw error;  // 抛出错误
    }
}

// 处理图片上传请求
router.post('/', upload.single('image'), (req, res) => {
    // 上传文件到七牛云
    const localFile = req.file.path;
    const key = req.file.originalname;
    const putExtra = new qiniu.form_up.PutExtra();
    formUploader.putFile(uploadToken, key, localFile, putExtra, (respErr, respBody, respInfo) => {
        if (respErr) {
            console.error(respErr);
            res.status(500).json({error: 'Failed to upload image to Qiniu Cloud.'});
        }
        if (respInfo.statusCode === 200) {
            // 上传成功，返回七牛云的图片地址
            const imageUrl = `https://cdn.xuxiao888.com/${key}`;
            res.json({imageUrl, code: 200});
        } else {
            console.error(respBody);
            res.status(500).json({error: 'Failed to upload image to Qiniu Cloud.'});
        }
    });
});
module.exports = {
    router,
    uploadImageToQiniu
};